<!--vue模板-->
<template>
  <!--工具栏-->
  <div class="toolbar">
    <el-button type="primary" size="small" @click="save">保存</el-button>
  </div>

  <!--基本信息-->
  <el-form>
    <el-row style="height: 40px; line-height: 40px">
      <el-col :span="24">&nbsp;&nbsp;基本信息</el-col>
    </el-row>

    <el-row>
      <el-col :span="2">单据主题:</el-col>
      <el-col :span="4">
        <el-input v-model="purchase.subject"></el-input>
      </el-col>
      <el-col :span="2">单据编号:</el-col>
      <el-col :span="4">
        <el-input :disabled="true" placeholder="保存后自动生成"></el-input>
      </el-col>
      <el-col :span="2">来源单据类型:</el-col>
      <el-col :span="4">
        <el-select
          class="m-2"
          placeholder="Select"
          v-model="purchase.sourceType"
        >
          <el-option
            v-for="item in sourceOptions"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-col>
      <el-col :span="2">来源单据:</el-col>
      <el-col :span="4">
        <el-input v-model="purchase.sourceSubject">
          <template #suffix>
            <el-icon class="el-input__icon"><search /></el-icon>
          </template>
        </el-input>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="2">采购申请类别:</el-col>
      <el-col :span="4">
        <el-select class="m-2" placeholder="Select" v-model="purchase.category">
          <el-option
            v-for="item in purchaseTypes"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-col>
      <el-col :span="2">是否需要询价:</el-col>
      <el-col :span="4">
        <el-radio-group class="ml-4" v-model="purchase.isenquiry">
          <el-radio :label="1" size="large">是</el-radio>
          <el-radio :label="0" size="large">否</el-radio>
        </el-radio-group>
      </el-col>
      <el-col :span="2">制单日期:</el-col>
      <el-col :span="4">
        <el-date-picker
          v-model="purchase.makeDate"
          type="date"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          placeholder="制单日期"
        />
      </el-col>
      <el-col :span="2">制单人员</el-col>
      <el-col :span="4">
        <el-input v-model="purchase.makeUser"></el-input>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="2">关联项目:</el-col>
      <el-col :span="4">
        <el-input v-model="purchase.project">
          <template #suffix>
            <el-icon class="el-input__icon"><search /></el-icon>
          </template>
        </el-input>
      </el-col>
      <el-col :span="2"></el-col>
      <el-col :span="4"></el-col>
      <el-col :span="2"></el-col>
      <el-col :span="4"></el-col>
      <el-col :span="2"></el-col>
      <el-col :span="4"></el-col>
    </el-row>

    <el-row style="height: 110px; line-height: 110px" class="btm">
      <el-col :span="2">备注:</el-col>
      <el-col :span="22">
        <el-input type="textarea" :rows="3" resize="none"></el-input>
      </el-col>
    </el-row>
  </el-form>

  <!--采购申请明细-->

  <div class="detail">
    采购申请明细
    <el-button type="primary" size="small" @click="add">增行</el-button>
    <el-button type="primary" size="small" @click="del">删行</el-button>
  </div>
  <el-table
    :data="tableData"
    style="width: 100%"
    stripe
    border
    @selection-change="chg"
    @cell-click="cellck"
  >
    <el-table-column
      type="selection"
      width="40"
      header-align="center"
      align="center"
    />
    <el-table-column
      type="index"
      label="序号"
      width="80"
      header-align="center"
      align="center"
    />
    <el-table-column
      label="产品名称"
      prop="productName"
      width="180"
      header-align="center"
    >
      <template v-slot="{ row, column, $index }">
        <el-input
          v-if="row.active && row.active.productName"
          size="small"
          v-model="row.productName"
          v-focus
        >
          <template #suffix>
            <el-icon
              class="el-input__icon"
              @click="tosearch(row.index)"
              style="cursor: pointer"
              ><search
            /></el-icon>
          </template>
        </el-input>
        <span v-else>{{ row.productName }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="产品编号"
      prop="productCode"
      width="160"
      header-align="center"
    />
    <el-table-column
      label="规格型号"
      prop="specification"
      width="180"
      header-align="center"
    />
    <el-table-column
      label="单位"
      prop="unit"
      width="80"
      header-align="center"
    />
    <el-table-column
      label="建议供应商"
      prop="supplier"
      width="180"
      header-align="center"
    >
      <template v-slot="{ row, column, $index }">
        <el-input
          v-if="row.active && row.active.supplier"
          v-model="row.supplier"
        ></el-input>
        <span v-else>{{ row.supplier }}</span>
      </template>
    </el-table-column>
    <el-table-column label="数量" prop="num" width="140" header-align="center">
      <template v-slot="{ row, column, $index }">
        <el-input-number
          style="width: 110px"
          :min="0"
          size="small"
          v-if="row.active && row.active.num"
          v-model="row.num"
        ></el-input-number>
        <span v-else>{{ row.num }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="单价"
      prop="price"
      width="140"
      header-align="center"
    >
      <template v-slot="{ row, column, $index }">
        <el-input-number
          style="width: 110px"
          size="small"
          :min="0"
          :precision="2"
          v-if="row.active && row.active.price"
          v-model="row.price"
        ></el-input-number>
        <span v-else>{{ row.price.toFixed(2) }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="总金额"
      prop="total"
      :min="0"
      width="140"
      header-align="center"
    >
      <template v-slot="{ row, column, $index }">
        <el-input-number
          :precision="2"
          style="width: 110px"
          size="small"
          v-if="row.active && row.active.total"
          v-model="row.total"
        ></el-input-number>
        <span v-else>{{ row.total.toFixed(2) }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="需用日期"
      prop="needDate"
      width="140"
      header-align="center"
    >
      <template v-slot="{ row, column, $index }">
        <el-date-picker
          v-if="row.active && row.active.needDate"
          v-model="row.needDate"
          style="width: 110px"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder=""
          size="small"
        />
        <span v-else>{{ row.needDate }}</span>
      </template>
    </el-table-column>
    <el-table-column label="备注" prop="note" header-align="center" width="200">
      <template v-slot="{ row, column, $index }">
        <el-input
          v-if="row.active && row.active.note"
          v-model="row.note"
        ></el-input>
        <span v-else>{{ row.note }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="库存信息"
      prop="store"
      width="180"
      header-align="center"
    />
  </el-table>

  <!--计算总金额 -->
  <el-row style="height: 50px; line-height: 50px">
    <el-col :span="4" style="text-align: right; padding-right: 10px">
      总金额:
    </el-col>
    <el-col :span="8">
      <el-input disabled v-model="purchase.money"></el-input>
    </el-col>
    <el-col :span="4" style="text-align: right; padding-right: 10px">
      数量合计:
    </el-col>
    <el-col :span="8">
      <el-input disabled v-model="totalnum"></el-input>
    </el-col>
  </el-row>


  <!--附件-->
  <attachment @refreshData="chgatt"></attachment>

  <!--选择产品-->
  <choose-product
    v-model:visible="isShowChooseProduct"
    @chooseProduct="chgproduct"
  ></choose-product>
</template>

<!--vue 组件选项定义-->
<script>
import { Search } from "@element-plus/icons-vue";
import ChooseProduct from "@/components/ChooseProduct.vue";
import Attachment from "../../components/Attachment.vue";
export default {
  data() {
    return {
      //来源
      sourceOptions: [],
      purchaseTypes:[],
      isShowChooseProduct: false, //是否显示选择产品
      purchase: {
        subject: "",
        money: 0,
        sourceType: "",
        sourceSubject: "",
        sourceId: "",
        category: "",
        isenquiry: 1,
        makeDate: "",
        makeUser: "",
        project: "",
        note: "",
        attachments: [],
      },
      totalnum: 0,
      tableData: [],
      selectItems: [], //用来存放用户选择的明细
      linenum: 10, //控制当前最多行
      currentIndex: 0, //当前正在编辑的行
    };
  },
  directives: {
    // 在模板中启用 v-focus
    focus: {
      mounted(el) {
        let items=el.getElementsByClassName("el-input__inner");
        if(items.length>0){
           items[0].focus();
        }
      }
    }
  },
  watch: {
    tableData: {
      handler: function (val) {

        //还原总金额和数量
        this.purchase.money = 0;
        this.totalnum = 0;
        //遍历数组
        val.forEach((el) => {
          if (el.price > 0 && el.num >= 0) {
            el.total = parseFloat(el.price) * parseInt(el.num);
            this.purchase.money += el.total;
            this.totalnum += parseInt(el.num);
          }
        });
      },
      deep: true, //深度侦听
    },
  },
  components: {
    Search,
    ChooseProduct,
    Attachment
  },
  created() {
    this.init();
    this.querySourceType();
  },
  methods: {

    chgatt(data){
        this.purchase.attachments=data;
    },

    //查询单据来源类型 
    querySourceType(){
       this.$http.get("/api/dict/queryDictByTypes",{types:"sourceType,purchaseType"})
       .then(res=>{
          if(res.code==200){
            this.sourceOptions=res.result['sourceType'];
            this.purchaseTypes=res.result['purchaseType'];
          }
       })
    },

    //选择产品后
    chgproduct(rs) {
      if (rs.length == 0) return;

      //获取选择结果的数量
      let count = rs.length;
      //更新n行
      let n = this.currentIndex + count - 1;

      let index = 0;

      //更新数据 从第currentIndex到n行
      for (let c = this.currentIndex; c <= n; c++) {
        //标志变量
        let flag = false; //默认代表在tableData中没有找到index对应的对象

        //更新一行数据
        for (let i = 0; i < this.tableData.length; i++) {
          let tmp = this.tableData[i];
          if (tmp.index == c) {
            //当前的tmp对象是正在编辑 的行  直接更新
            this.updateRow(tmp, index, rs);
            index++;
            flag = true;
            break;
          }
        }

        //在已有表格数据没有找到
        if (!flag) {
          //增加一行
          this.add();
          //直接更新最后一行
          let tmp = this.tableData[this.tableData.length - 1];
          this.updateRow(tmp, index, rs);
          index++;
        }
      }

      console.log(this.tableData);
    },

    //更新行数据
    updateRow(tmp, index, rs) {
      //当前的tmp对象是正在编辑 的行  直接更新
      tmp.productId = rs[index].id;
      tmp.productName = rs[index].name;
      tmp.productCode = rs[index].code;
      tmp.specification = rs[index].specification;
      tmp.price = rs[index].price;
      tmp.unit = rs[index].unit;
    },

    tosearch(index) {
      this.isShowChooseProduct = true;
      this.currentIndex = index;
    },
    //保存方法
    save() {
      //过滤明细
      let tmp = [];
      this.tableData.forEach((el) => {
        if (el.productName) {
          tmp.push(el);
        }
      });

      if (tmp.length == 0) {
        this.$message.warning("请选择要采购的产品！");
        return;
      }
      //增加明细
      this.purchase.purchaseDetails = tmp;

      //保存
      this.$http.post("/api/purchase/save", this.purchase).then((res) => {
        if (res.code == 200) {
          this.$message.success("保存成功");
          this.$router.push("/purchase");
        }
      });
    },

    init() {
      for (let i = 1; i <= this.linenum; i++) {
        let tmp = {
          index: i,
          productId: "",
          productName: "",
          productCode: "",
          specification: "",
          unit: "",
          supplierId: "",
          supplier: "",
          num: 0,
          price: 0,
          total: 0,
          needDate: "",
          note: "",
          store: "",
        };
        this.tableData.push(tmp);
      }
    },
    add() {
      this.linenum++;
      this.tableData.push({
        index: this.linenum,
        productId: "",
        productName: "",
        productCode: "",
        specification: "",
        unit: "",
        supplierId: "",
        supplier: "",
        num: 0,
        price: 0,
        total: 0,
        needDate: "",
        note: "",
        store: "",
      });
    },

    //单元格点击事件
    cellck(row, column, cell, event) {
      this.hf();
      if (column.property != undefined) {
        row.active = {};
        row.active[column.property] = true;
      }
    },

    //恢复数据
    hf() {
      this.tableData.forEach((el) => {
        el.active = {};
      });
    },

    //输入框失去焦点
    disactive(row) {
      row.active = false;
    },
    //当选项发生变化时
    chg(sel) {
      this.selectItems = [];
      //遍历选中的复选框
      sel.forEach((el) => {
        this.selectItems.push(el.index);
      });
    },
    //删除行
    del() {
      if (this.selectItems.length == 0) {
        this.$message.warning("请选择要删除的行！");
        return;
      }

      this.$confirm("你确定要删除吗?", "提示")
        .then((res) => {
          let tmp = []; //用来存放未删除的数据
          //遍历表格数据
          this.tableData.forEach((el) => {
            console.log( el.index);
            //判断当前行是否要删除
            if (this.selectItems.indexOf(el.index) == -1) {
              //没找到 说明当前行不要是要删除的 保存到临时对象里tmp
              tmp.push(el);
            }
          });

          //更新表格行 
          
          this.tableData = tmp;
          console.log("this.tableData>>", this.tableData);
        })
        .catch((err) => {});
    },
  },
};
</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped>
:deep(.el-row) {
  border: #c0ccdd solid 1px;
  border-bottom-style: none;
  height: 50px;
  line-height: 50px;
  background-color: #f9fcff;
}
:deep(.el-col-2) {
  text-align: right;
  padding-right: 10px;
}

:deep(.el-textarea) {
  vertical-align: middle;
}
.btm {
  border-bottom: #c0ccdd solid 1px;
}

.detail {
  height: 40px;
  line-height: 40px;
  border: #c0ccdd solid 1px;
  background-color: #f9fcff;
  margin-top: 20px;
  padding-left: 10px;
  border-bottom-style: none;
}

.toolbar {
  height: 40px;
  line-height: 40px;
  margin-bottom: 15px;
}
</style>
